package com.heima.kafka.sample;

import org.apache.kafka.clients.consumer.*;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消息的消费者
 */
public class ConsumerQuickStart {

    public static void main(String[] args) {

        //kafka配置
        Properties properties = new Properties();
        //链接地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"121.4.86.29:9092");
        //反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");

        //消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"group-2");

        //设置手动提交偏移量
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");

        //消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        //订阅主题
        consumer.subscribe(Collections.singletonList("kafka-topic"));

        /*while (true){
            //拉取消息
            ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println(consumerRecord.key());
                System.out.println(consumerRecord.value());
                System.out.println(consumerRecord.offset());
                System.out.println("分区："+consumerRecord.partition());
            }
        }*/

        while (true){
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record.value());
                System.out.println(record.key());
                try {
                    consumer.commitSync();//同步提交当前最新的偏移量
                }catch (CommitFailedException e){
                    System.out.println("记录提交失败的异常："+e);
                }

            }
        }

    }
}
